package springboot.demo.shiro.config;

import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import springboot.demo.shiro.shiro.CustomRealm;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>Project: springboot-demo </p>
 * 
 * <p>Function:  </p>
 * 
 * <p>Description:  </p>
 * 
 * @author weiqiang.li
 * 
 * @date 2018/11/23
 * 
 * @version 1.0
 */

//@Configuration
public class ShiroConfig {

    /**
     * 权限管理，配置Realm
     * @author weiqiang.li
     * @date 2018/11/23
     * @return SecurityManager
     */
    @Bean
    public SecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(customRealm());
        return securityManager;
    }

    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        // 设置登陆url
        shiroFilterFactoryBean.setLoginUrl("/tologin");
        // 设置未授权url
        shiroFilterFactoryBean.setUnauthorizedUrl("/unauth");

        // 设置拦截策略
        Map<String, String> filterChainDefinitionMap = new HashMap<>();
        filterChainDefinitionMap.put("/tologin", "anon");
        filterChainDefinitionMap.put("/login", "anon");
        filterChainDefinitionMap.put("/unauth", "authc");

        filterChainDefinitionMap.put("/user/getList", "perms[*:*:*]");

        filterChainDefinitionMap.put("/**", "authc");

        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);

        return shiroFilterFactoryBean;
    }

    /**
     * 注入自定义realm
     * @return CustomRealm
     */
    @Bean
    public CustomRealm customRealm() {
        return new CustomRealm();
    }
}
